  
#include <stdio.h>
#include <stdlib.h>
#include <string.h>




/* This is the recursive function that is the bread and butter of the programs
   formatting. It takes in a node from the double array created in main,
   and prints the node then all of it's children, using the same function */

int printTree(int start, int processes[][2], int indent, int size_of_p){
  int i;

  for(i = 0; i < indent; i++)
    printf("   ");
  printf("%i\n", start);

  for(i = 0; i < size_of_p; i++){
    if (processes[i][1] == start){
      printTree(processes[i][0], processes, ++indent, size_of_p);

      //reset indent to it's previous value
      --indent;
    }
  }
  
  return 0;

}

int main(){
  int num_processes = 0;
  char *tok;
  char * line;
  int i;
  char buf[1024];
  FILE * ps_pipe = popen("ps -afe", "r");


  //Get the total length of the ps command, for use in the double array
  while(fgets(buf,sizeof(buf), ps_pipe)) num_processes++;
  pclose(ps_pipe);
  
  printf("Read %i lines of output from ps\n", num_processes);


  ps_pipe = popen("ps -afe", "r");
  

  /* Create double array of ints, with PID in the 0th location and PPID
     in the 1st */
  int processes [num_processes][2];
  

  //Reset it to 0, in order to have a counter throughout the program
  num_processes = 0;

  if (ps_pipe){
    
    //Skip the first line of input, as it's just the header
    line = fgets(buf, sizeof(buf), ps_pipe);

    while (line = fgets(buf,sizeof(buf), ps_pipe)){

      //Initialize the token and skip the first three, as they are useless
      tok = strtok(line, " ");
      tok = strtok(NULL, " ");
      tok = strtok(NULL, " ");
      tok = strtok(NULL, " ");



      //printf ("Read %i \n",num_processes);
      for(i = 0; i < 2; i++){

	/* Corrects errors that occur when using atoi with negative numbers,
	   as Minix-3 surrounds them in parenthesis, e.g., (-1). */


	if(tok[0] == '('){
	  tok = "-1";
	  int j;
	  for(j = 0; j < num_processes; j++)
	    processes[j][i] = - num_processes +j -1;

	  

	}


	processes[num_processes][i] = atoi(tok);
	
	tok = strtok(NULL, " ");	
      }
      num_processes++;
    }

    //printf("Read %i lines of output from ps\n", num_processes);
    pclose(ps_pipe);

    printTree(0, processes, 0, num_processes);
    
  }
  

  else printf("Error, ps_pipe failed");

  return 0;

}
